package com.example.control.regisControl;

import com.example.control.CommentControl;
import com.example.domain.t_user;
import com.example.service.AsyncService;
import com.example.service.IUserService;
import com.example.utils.MailUtils;
import com.example.utils.myUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
@Transactional
public class regiscontrol {
    private static final Logger logger= (Logger) LoggerFactory.getLogger(CommentControl.class);

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redis;
    @Autowired
    private IUserService iuse;
    //异步线程
    @Autowired
    private AsyncService asyncService;
    //邮箱
    @Autowired
    private MailUtils mailUtils;

    @RequestMapping({"/register","/register.html"})
    public String register(){
        return "comm/register";
    }
    //判断用户名是否存在
    @RequestMapping("/regis/register_username")
    @ResponseBody
    public boolean regis_username(String username){
        return iuse.Select(username)==null;
    }
    //判断邮箱是否存在
    @RequestMapping("/regis/register_email")
    @ResponseBody
    public boolean regis_email(String email){
        return iuse.SelectEmail(email)==null;
    }

    @RequestMapping("/regis/register")
    @ResponseBody
    //注册验证，并保存用户，发送验证邮箱
    public String regis(String username,String password,String email,
                            HttpServletRequest request){
        t_user user = new t_user();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setCreated(new Date());
        user.setValid(false);
        if(iuse.Select(username)!=null)return "存在用户名";
        if(iuse.SelectEmail(email)!=null)return "存在邮箱";
        //发送验证码
        StringBuffer requestURL = request.getRequestURL();
        int i=requestURL.length()-1;
        for(;i>=0;i--){
            if(requestURL.charAt(i)=='/'){
                break;
            }
        }
        String x = myUtils.getString(20);

        String url=request.getRequestURL().substring(0,i)+"/cheek_email?id="+email+"&success="+ x;
        try{
            redis.opsForValue().set(email,x);
        }catch (Exception e){
            logger.error("redis 缓存出错，错误信息："+e.getMessage());
            return "注册失败，练习管理员";
        }
        try{
            asyncService.asyncInvoke(()->{
                boolean send =  mailUtils.sendMail(email, "<a href='" + url + "'>你注册了" + username + "，点击此处，激活账号</a>", "注册申请验证邮箱");
                if(!send){
                    logger.error("发送邮箱"+email+"失败了");
                }else{
                    logger.info("发送邮箱"+email+"成功");
                }

            });
        }catch(Exception e){
            logger.error("异步线程发送邮箱失败，错误信息："+e.getMessage());
        }
        iuse.insert(user);
        return "注册成功请注意激活账号";

    }
    //检查邮箱验证码
    @RequestMapping("/regis/cheek_email")
    @ResponseBody
    public String cheek(String id,String success,
                        HttpServletRequest request){
        String requestURL = String.valueOf(request.getRequestURL());
        String s = requestURL.replace(request.getServletPath(), "");
        String o=null;
        try{

            o = (String) redis.opsForValue().get(id);

        }catch (Exception e){
            logger.error("redis 缓存出错，错误信息："+e.getMessage());
            return "comm/send_register?error=服务器错误，请联系管理员。";
        }
        //System.out.println(success+","+o);
        if(o!=null&&o.equals(success)) {
            iuse.setVail(id,true);
            redis.opsForValue().set(id,null);
            logger.info("注册了新用户-email："+id);
            return "<h1 align='center'><a href='/login?url="+s+"'>成功,去登陆</a></h1>";
        }
        return "comm/send_register?error=验证失败";
    }

    //重新发送验证码
    @RequestMapping("/regis/againRegis")
    @ResponseBody
    public String againRegis(String email,HttpServletRequest request){
        StringBuffer requestURL = request.getRequestURL();
        if(iuse.SelectEmail(email).isValid())return "该用户已经激活，无需激活";
        int i=requestURL.length()-1;
        for(;i>=0;i--){
            if(requestURL.charAt(i)=='/'){
                break;
            }
        }
        String x = myUtils.getString(20);

        String url=request.getRequestURL().substring(0,i)+"/cheek_email?id="+email+"&success="+ x;
        try{
            redis.opsForValue().set(email,x);
        }catch (Exception e){
            logger.error("redis 缓存出错，错误信息："+e.getMessage());
            return "发送失败，请联系管理员";
        }
        try{
            asyncService.asyncInvoke(()->{
                mailUtils.sendMail(email,"<a href='"+url+"'>点击此处，激活账号</a>","注册申请验证邮箱");

            });
        }catch(Exception e){
            logger.error("异步线程发送邮箱失败，错误信息："+e.getMessage());
        }
        return "发送成功";
    }
}
